package com.wenhai.spring.validation;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.context.MessageSource;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Locale;

/**
 * {@link Errors} 演示示例
 *
 * @author wenhai
 * @date 2020/10/14
 */
public class ErrorsMessageDemo {
    public static void main(String[] args) {
        // 0. 构建 User 对象
        User user = new User();
        // 1. 选择 Errors 实现 BeanPropertyBindingResult
        Errors errors = new BeanPropertyBindingResult(user, "user");
        // 2. 验证 User 对象
        errors.reject("user.property.not.null");
        // 3. 验证 User 属性
        errors.rejectValue("beanName", "beanName.required");
        // 4. 取出 errorsMessage
        List<ObjectError> allErrors = errors.getAllErrors();
        MessageSource ms = createMessageSource();
        ObjectError globalError = errors.getGlobalError();
        System.out.println("=========globalError========");
        System.out.println(ms.getMessage(globalError.getCode(), globalError.getArguments(), Locale.getDefault()));
        FieldError fieldError = errors.getFieldError();
        System.out.println("=========fieldError========");
        System.out.println(ms.getMessage(fieldError.getCode(), fieldError.getArguments(), Locale.getDefault()));

        System.out.println("=========allErrors========");
        for (ObjectError error : allErrors) {
            System.out.println(ms.getMessage(error.getCode(), error.getArguments(), Locale.getDefault()));
        }
    }

     static MessageSource createMessageSource() {

        StaticMessageSource sms = new StaticMessageSource();
        sms.addMessage("user.property.not.null", Locale.getDefault(), "User 所有属性不能为空");
        sms.addMessage("beanName.required", Locale.getDefault(), "the name of User must be not null");

        return sms;
    }
}
